package com.hxzy.servlet.message;

import com.hxzy.bean.Message;
import com.hxzy.service.MessageService;
import com.hxzy.service.impl.MessageServiceImpl;
import com.hxzy.util.PageUtil;
import com.hxzy.vo.JsonResult;
import com.hxzy.vo.MessageVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author nick
 */
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        //从request请求中获取当前页的页码，如果没有，则说明第一次查询
        String pageIndex_str = req.getParameter("pageIndex");

        int pageIndex = PageUtil.DEFAULT_PAGE_INDEX;
        if (Objects.nonNull(pageIndex_str)) { //参数不为null，说明页面传递了一个页码过来，因此我们需要根据这个页码查询数据
            pageIndex = Integer.parseInt(pageIndex_str);
        }

        //调用业务逻辑层的实例
        MessageService service = new MessageServiceImpl();
        //查询所有的留言信息

        PageUtil pageUtil = new PageUtil(pageIndex); //查询指定页码
        PageUtil<MessageVo> messageVoPageUtil = service.queryAllMessage(pageUtil);

        /*//将留言集合添加到request作用域
        req.setAttribute("page",messageVoPageUtil);

        //页面转发，将包含了留言信息集合的request作用域转发到index.jsp页面
        req.getRequestDispatcher("/index.jsp").forward(req, resp);*/

        JsonResult.write2client(messageVoPageUtil,resp);

    }
}
